package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Page;
import com.example.springboot.entity.*;
import com.example.springboot.mapper.*;
import com.example.springboot.service.OrdersService;
import com.example.springboot.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表(Orders)表服务实现类
 *
 * @author makejava
 * @since 2024-01-13 17:16:26
 */
@Service("ordersService")
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrdersProductServiceImpl ordersProductService;
    @Autowired
    private OrdersProductMapper ordersProductMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private UserMapper userMapper;


    /**
     * 获取最近一周的订单
     *
     * @return
     */
    @Override
    public List<Orders> selectRecentWeek() {
        try {
            // 获取最近一周的时间范围
            String startTimeStr = DateUtil.getStartOfRecentDaysAsString(7);
            String endTimeStr = DateUtil.getEndOfRecentDaysAsString();
            Date startTime = DateUtil.getTodayStartTime(startTimeStr);
            Date endTime = DateUtil.getTodayEndTime(endTimeStr);
            return ordersMapper.selectRecentWeek(startTime, endTime);
        } catch (Exception e) {
            throw new ServiceException("获取最近一周的订单失败");
        }
    }

    /**
     * 获取所有商家信息
     *
     * @return
     */
    @Override
    public List<Orders> selectAll() {
        try {
            return ordersMapper.selectAll();
        } catch (Exception e) {
            throw new ServiceException("查询失败");
        }
    }

    /**
     * 根据ID删除
     *
     * @param id
     */
    @Transactional
    @Override
    public void deleteById(Integer id) {
        try {
            // 获取订单和商品的关系
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByOrderId(id);
            ordersMapper.deleteById(id);
            // 订单删除后，那么我需要把商品的销量和库存变回去
            // 销量减去购买的数量
            // 库存加上购买的数量
            for (OrdersProduct ordersProduct : ordersProducts) {
                Product product = ordersProduct.getProduct();
                product.setStock(product.getStock().add(new BigDecimal(ordersProduct.getNum())));
                product.setSales(product.getSales().subtract(new BigDecimal(ordersProduct.getNum())));
                productMapper.update(product);
            }
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }


    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public Page<Orders> selectByPage(Integer currentPage, Integer pageSize) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = ordersMapper.selectAll().size();
            // 查询分页数据
            List<Orders> users = ordersMapper.selectByPage(startRow, pageSize);

            // 封装返回结果
            Page<Orders> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("分页查询失败！");
        }

    }


    /**
     * 分页查询 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param number
     * @param username
     * @param storeName
     * @param status
     * @return
     */
    @Override
    public Page<Orders> selectByManyConditionInpage(Integer currentPage, Integer pageSize, String number, String username, String storeName, String startTime, String endTime, Integer status) {

        try {

            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            int totalCount = 0;
            List<Orders> orders = new ArrayList<>();
            if (StrUtil.isBlank(storeName)) {
                // 商家参数为空
                // 直接调用ordersMapper查询
                // 查询总记录数
                totalCount = ordersMapper.selectByManyCondition(number, username, startTime, endTime, status).size();
                // 查询分页数据
                orders = ordersMapper.selectByManyConditionInpage(startRow, pageSize, number, username, startTime, endTime, status);
            } else {
                // 商家参数不为空
                // 获取商家的id
                Store store = storeMapper.selectByName(storeName);
                // 查询商家的所有商品
                List<Product> products = productMapper.selectByStoreId(store.getId());
                // 互获取商品的ids
                List<Integer> productIds = products.stream().map(Product::getId).distinct().collect(Collectors.toList());
                // 根据商品id查找订单id，去重
                List<Integer> ordersIds = new ArrayList<>();
                for (Integer productId : productIds) {
                    List<OrdersProduct> ordersProducts = ordersProductMapper.selectByProductId(productId);
                    for (OrdersProduct ordersProduct : ordersProducts) {
                        ordersIds.add(ordersProduct.getOrdersId());
                    }
                }
                //  去重
                ordersIds = ordersIds.stream().distinct().collect(Collectors.toList());
                // 查询总记录数
//                totalCount = ordersIds.size();
                // 查询总记录数
                totalCount = ordersMapper.selectOrderCountByManyConditionInIds(number, username, startTime, endTime, status, ordersIds);
                // 查询其他条件的下的商家订单
                orders = ordersMapper.selectByManyConditionInpageInIds(startRow, pageSize, number, username, startTime, endTime, status, ordersIds);

            }
            // 封装返回结果
            Page<Orders> page = new Page<>();
            page.setList(orders);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("条件查询失败！");
        }

    }

    /**
     * 分页查询 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param number
     * @param username
     * @param storeName
     * @return
     */
    @Override
    public Page<Orders> selectByManyConditionNoStatusInpage(Integer currentPage, Integer pageSize, String number, String username, String startTime, String endTime, String storeName) {
        try {

            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            int totalCount = 0;
            List<Orders> orders = new ArrayList<>();
            if (StrUtil.isBlank(storeName)) {
                // 商家参数为空
                // 直接调用ordersMapper查询
                // 查询总记录数
                totalCount = ordersMapper.selectByManyConditionNoStatus(number, username, startTime, endTime).size();
                // 查询分页数据
                orders = ordersMapper.selectByManyConditionNoStatusInpage(startRow, pageSize, number, username, startTime, endTime);
            } else {
                // 商家参数不为空
                // 获取商家的id
                Store store = storeMapper.selectByName(storeName);
                // 查询商家的所有商品
                List<Product> products = productMapper.selectByStoreId(store.getId());
                // 互获取商品的ids
                List<Integer> productIds = products.stream().map(Product::getId).distinct().collect(Collectors.toList());
                // 根据商品id查找订单id，去重
                List<Integer> ordersIds = new ArrayList<>();
                for (Integer productId : productIds) {
                    List<OrdersProduct> ordersProducts = ordersProductMapper.selectByProductId(productId);
                    for (OrdersProduct ordersProduct : ordersProducts) {
                        ordersIds.add(ordersProduct.getOrdersId());
                    }
                }
                ordersIds = ordersIds.stream().distinct().collect(Collectors.toList());
                // 查询总记录数
                Integer status = null;
                totalCount = ordersMapper.selectOrderCountByManyConditionInIds(number, username, startTime, endTime, status, ordersIds);
                // 查询其他条件的下的商家订单
                orders = ordersMapper.selectByManyConditionNoStatusInpageInIds(startRow, pageSize, number, username, startTime, endTime, ordersIds);
            }
            // 封装返回结果
            Page<Orders> page = new Page<>();
            page.setList(orders);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("条件查询失败！");
        }

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        try {
            for (Integer id : ids) {
                ordersMapper.deleteById(id);
            }
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }

    /**
     * 根据id查询商家
     *
     * @param id
     * @return
     */
    @Override
    public Orders selectById(Integer id) {
        try {
            return ordersMapper.selectById(id);
        } catch (Exception e) {
            throw new ServiceException("商家不存在");
        }
    }

    /**
     * 根据分类ID获取该分类下的订单数量
     *
     * @param id
     * @return
     */
    @Override
    public BigDecimal selectOrderCountByCategoryId(Integer id) {
        BigDecimal result = new BigDecimal(0);
        Set<Integer> productIds = new HashSet<>();
        try {
            // 根据分类ID找到商品ID集合
            List<Product> products = productMapper.selectProDuctByCategoryId(id);
            // 获取该分类下商品的所有ID集合
            productIds = products.stream().map(Product::getId).collect(Collectors.toSet());
        } catch (Exception e) {
            throw new ServiceException("查询分类下商品失败");
        }
        try {
            for (Integer productId : productIds) {
                // 通过orders_product关系表统计该所有商品下订单的count(*)
                result = result.add(ordersProductService.selectOrderCountByProductId(productId));
            }
        } catch (Exception e) {
            throw new ServiceException("查询分类下订单数量失败");
        }
        return result;
    }

    @Override
    public long getTotal() {
        try {
            return ordersMapper.getTotal();
        } catch (Exception e) {
            throw new ServiceException("查询订单总数失败");
        }
    }

    @Override
    public Page<Orders> loadUserOrders(Integer currentPage, Integer pageSize, Integer id) {
        try {

            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            Page<Orders> page = new Page<>();
            List<Orders> orders = ordersMapper.loadUserOrders(startRow, pageSize, id);
            int total = ordersMapper.getTotalByUserId(id);
            page.setList(orders);
            page.setTotal(total);
            return page;
        } catch (Exception e) {
            throw new ServiceException("查询用户订单失败");
        }
    }


    @Override
    public Page<Orders> loadStoreOrders(Integer currentPage, Integer pageSize, Integer id) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            Page<Orders> page = new Page<>();
            List<Orders> orders = ordersMapper.loadStoreOrders(startRow, pageSize, id);
            int total = ordersMapper.getStoreTotal(id);
            page.setList(orders);
            page.setTotal(total);
            return page;
        } catch (Exception e) {
            throw new ServiceException("查询商家订单失败");
        }
    }

    @Override
    public int getStoreTotal(Integer id) {
        try {
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByStoreId(id);
            return ordersProducts.size();
        } catch (Exception e) {
            throw new ServiceException("查询商家订单总数失败");
        }
    }

    @Override
    public List<Orders> selectStoreRecentWeek(Integer id) {
        try {

            // 获取最近一周的时间范围
            Date startTime = DateUtil.getStartOfLastWeek();
            Date endTime = DateUtil.getEndOfToday();
            // 先获取商家的所有订单
            Integer storeId = id;
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByStoreId(storeId);
            List<Integer> ordersIds = ordersProducts.stream().map(OrdersProduct::getOrdersId).distinct().collect(Collectors.toList());
            if (ordersIds.size() > 0) {
                List<Orders> orders = ordersMapper.selectRecentWeek(startTime, endTime);
                // 过滤出商家订单
                List<Orders> storeOrders = orders.stream()
                        .filter(o -> ordersIds.contains(o.getId()))
                        .collect(Collectors.toList());
                return storeOrders;
            } else {
                return new ArrayList<Orders>();
            }
        } catch (Exception e) {
            throw new ServiceException("获取最近一周的订单失败");
        }
    }

    @Override
    public Page<Orders> selectByPageInStore(Integer currentPage, Integer pageSize, Integer id) {
        try {

            //


            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            // 查询订单列表
            List<Orders> orders = ordersMapper.loadStoreOrders(startRow, pageSize, id);
            // 查询订单总数
            Integer total = ordersMapper.getStoreTotal(id);
            Page<Orders> page = new Page<>();
            page.setList(orders);
            page.setTotal(total);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("分页查询商家订单失败");
        }
    }

    @Override
    public Page<Orders> getOrdersByUserId(Integer currentPage, Integer pageSize, Integer userId) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询订单总数
            int total = ordersMapper.getOrdersTotalByUserId(userId);
            // 分页查询订单信息
            List<Orders> orders = ordersMapper.getOrdersByUserId(startRow, pageSize, userId);
            for (Orders order : orders) {
                // 获取该订单Id下的订单与商品的关系集合
                List<OrdersProduct> ordersProducts = ordersProductMapper.selectByOrderId(order.getId());
                // 取出ordersProducts集合中的商品集合
                List<Product> products = ordersProducts.stream().map(OrdersProduct::getProduct).collect(Collectors.toList());
                // 将商品加入订单的products中
                order.setProducts(products);
            }
            Page<Orders> page = new Page<>();
            page.setTotal(total);
            page.setList(orders);
            return page;
        } catch (Exception e) {
            throw new ServiceException("分页查询用户订单失败");
        }
    }

    @Override
    public Page<Orders> searchByPayStatusAndUserId(Integer currentPage, Integer pageSize, Integer payStatus, Integer userId) {
        try {

            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询订单总数
            int total = ordersMapper.searchCountByPayStatusAndUserId(payStatus, userId);
            // 分页查询订单信息
            List<Orders> orders = ordersMapper.searchByPayStatusAndUserId(startRow, pageSize, payStatus, userId);
            for (Orders order : orders) {
                // 获取该订单Id下的订单与商品的关系集合
                List<OrdersProduct> ordersProducts = ordersProductMapper.selectByOrderId(order.getId());
                // 取出ordersProducts集合中的商品集合
                List<Product> products = ordersProducts.stream().map(OrdersProduct::getProduct).collect(Collectors.toList());
                // 将商品加入订单的products中
                order.setProducts(products);
            }
            Page<Orders> page = new Page<>();
            page.setTotal(total);
            page.setList(orders);
            return page;

        } catch (Exception e) {
            throw new ServiceException("分页查询用户订单失败");
        }
    }

    @Override
    public Orders loadOrderByOrderId(Integer orderId) {
        try {
            Orders orders = ordersMapper.selectById(orderId);
            // 获取该订单Id下的订单与商品的关系集合
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByOrderId(orders.getId());
            // 取出ordersProducts集合中的商品集合
            List<Product> products = ordersProducts.stream().map(OrdersProduct::getProduct).collect(Collectors.toList());
            // 将商品加入订单的products中
            orders.setProducts(products);
            return orders;
        } catch (Exception e) {
            throw new ServiceException("查询用户订单失败");
        }
    }

    @Override
    public Orders addOrders(Orders orders) {
        try {
            ordersMapper.addOrders(orders);
            // 创建订单后，
            return orders;
        } catch (Exception e) {
            throw new ServiceException("添加订单失败");
        }
    }

    @Override
    public void confirmReceipt(Integer id) {
        try {
            Integer status = 6;
            ordersMapper.updateStatus(id, status);
        } catch (Exception e) {
            throw new ServiceException("确认收货失败");
        }
    }

    @Override
    public void send(Integer id) {
        try {
            // 发货 = 更新当前订单与商品的关系表中的发货状态

        } catch (Exception e) {
            throw new ServiceException("发货失败");
        }
    }

    @Override
    public User selectUserById(Integer id) {
        try {
            Orders orders = ordersMapper.selectById(id);
            Integer userId = orders.getUserId();
            return userMapper.selectById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询用户信息失败");
        }
    }


}
